using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 查询处理器
    /// 负责处理和解析用户查询，提取关键信息
    /// </summary>
    public class QueryProcessor
    {
        private Dictionary<string, QueryContext> contextKeywords;
        private HashSet<string> stopWords;
        private Dictionary<string, float> keywordWeights;
        
        public QueryProcessor()
        {
            InitializeProcessor();
        }
        
        /// <summary>
        /// 初始化查询处理器
        /// </summary>
        private void InitializeProcessor()
        {
            // 初始化上下文关键词
            contextKeywords = new Dictionary<string, QueryContext>
            {
                // 对话相关
                { "conversation", QueryContext.Conversation },
                { "chat", QueryContext.Conversation },
                { "talk", QueryContext.Conversation },
                { "discuss", QueryContext.Conversation },
                { "said", QueryContext.Conversation },
                { "told", QueryContext.Conversation },
                
                // 计划相关
                { "plan", QueryContext.Planning },
                { "planning", QueryContext.Planning },
                { "schedule", QueryContext.Planning },
                { "goal", QueryContext.Planning },
                { "intention", QueryContext.Planning },
                { "want", QueryContext.Planning },
                { "need", QueryContext.Planning },
                
                // 反思相关
                { "reflection", QueryContext.Reflection },
                { "reflect", QueryContext.Reflection },
                { "think", QueryContext.Reflection },
                { "thought", QueryContext.Reflection },
                { "realize", QueryContext.Reflection },
                { "understand", QueryContext.Reflection },
                
                // 社交相关
                { "friend", QueryContext.Social },
                { "relationship", QueryContext.Social },
                { "social", QueryContext.Social },
                { "meet", QueryContext.Social },
                { "together", QueryContext.Social },
                
                // 导航相关
                { "location", QueryContext.Navigation },
                { "place", QueryContext.Navigation },
                { "where", QueryContext.Navigation },
                { "go", QueryContext.Navigation },
                { "move", QueryContext.Navigation }
            };
            
            // 初始化停用词
            stopWords = new HashSet<string>
            {
                "the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", 
                "of", "with", "by", "is", "was", "are", "were", "be", "been", "have", 
                "has", "had", "do", "does", "did", "will", "would", "could", "should",
                "this", "that", "these", "those", "i", "you", "he", "she", "it", "we", "they"
            };
            
            // 初始化关键词权重
            keywordWeights = new Dictionary<string, float>
            {
                // 高权重关键词
                { "important", 1.5f },
                { "urgent", 1.5f },
                { "critical", 1.5f },
                { "remember", 1.3f },
                { "forget", 1.3f },
                { "love", 1.2f },
                { "hate", 1.2f },
                { "angry", 1.2f },
                { "happy", 1.2f },
                { "sad", 1.2f },
                
                // 中等权重关键词
                { "like", 1.1f },
                { "dislike", 1.1f },
                { "enjoy", 1.1f },
                { "prefer", 1.1f },
                { "work", 1.0f },
                { "home", 1.0f },
                { "family", 1.1f },
                { "friend", 1.1f }
            };
        }
        
        /// <summary>
        /// 处理查询
        /// </summary>
        public ProcessedQuery ProcessQuery(string query, QueryContext? contextHint = null)
        {
            if (string.IsNullOrEmpty(query))
            {
                return new ProcessedQuery
                {
                    originalQuery = "",
                    cleanedQuery = "",
                    keywords = new List<string>(),
                    context = QueryContext.General,
                    embedding = null
                };
            }
            
            try
            {
                var processedQuery = new ProcessedQuery
                {
                    originalQuery = query,
                    cleanedQuery = CleanQuery(query),
                    context = contextHint ?? DetermineQueryContext(query),
                    timestamp = DateTime.Now
                };
                
                // 提取关键词
                processedQuery.keywords = ExtractKeywords(processedQuery.cleanedQuery);
                
                // 计算查询的重要性分数
                processedQuery.importanceScore = CalculateQueryImportance(processedQuery);
                
                // 提取实体
                processedQuery.entities = ExtractEntities(processedQuery.cleanedQuery);
                
                // 检测查询意图
                processedQuery.intent = DetectQueryIntent(processedQuery.cleanedQuery, processedQuery.context);
                
                return processedQuery;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[QueryProcessor] Error processing query '{query}': {ex.Message}");
                return new ProcessedQuery
                {
                    originalQuery = query,
                    cleanedQuery = query,
                    keywords = new List<string>(),
                    context = QueryContext.General,
                    embedding = null
                };
            }
        }
        
        /// <summary>
        /// 清理查询文本
        /// </summary>
        private string CleanQuery(string query)
        {
            // 转换为小写
            var cleaned = query.ToLower();
            
            // 移除标点符号
            cleaned = System.Text.RegularExpressions.Regex.Replace(cleaned, @"[^\w\s]", " ");
            
            // 合并多个空格
            cleaned = System.Text.RegularExpressions.Regex.Replace(cleaned, @"\s+", " ");
            
            // 去除首尾空格
            cleaned = cleaned.Trim();
            
            return cleaned;
        }
        
        /// <summary>
        /// 确定查询上下文
        /// </summary>
        private QueryContext DetermineQueryContext(string query)
        {
            var lowerQuery = query.ToLower();
            var contextScores = new Dictionary<QueryContext, float>();
            
            // 初始化所有上下文分数
            foreach (QueryContext context in Enum.GetValues(typeof(QueryContext)))
            {
                contextScores[context] = 0f;
            }
            
            // 基于关键词计算上下文分数
            foreach (var kvp in contextKeywords)
            {
                if (lowerQuery.Contains(kvp.Key))
                {
                    contextScores[kvp.Value] += 1f;
                    
                    // 如果关键词在查询开头，给予额外权重
                    if (lowerQuery.StartsWith(kvp.Key))
                    {
                        contextScores[kvp.Value] += 0.5f;
                    }
                }
            }
            
            // 基于查询模式检测上下文
            if (lowerQuery.Contains("what") && lowerQuery.Contains("think"))
            {
                contextScores[QueryContext.Reflection] += 1f;
            }
            
            if (lowerQuery.Contains("who") && (lowerQuery.Contains("with") || lowerQuery.Contains("talk")))
            {
                contextScores[QueryContext.Social] += 1f;
            }
            
            if (lowerQuery.Contains("when") || lowerQuery.Contains("time"))
            {
                contextScores[QueryContext.Planning] += 0.5f;
            }
            
            if (lowerQuery.Contains("where") || lowerQuery.Contains("location"))
            {
                contextScores[QueryContext.Navigation] += 1f;
            }
            
            // 返回得分最高的上下文
            var maxScore = contextScores.Values.Max();
            if (maxScore > 0)
            {
                return contextScores.First(kvp => kvp.Value == maxScore).Key;
            }
            
            return QueryContext.General;
        }
        
        /// <summary>
        /// 提取关键词
        /// </summary>
        public List<string> ExtractKeywords(string cleanedQuery, int maxKeywords = 10)
        {
            if (string.IsNullOrEmpty(cleanedQuery))
                return new List<string>();
            
            var words = cleanedQuery.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var keywordScores = new Dictionary<string, float>();
            
            foreach (var word in words)
            {
                // 跳过停用词和短词
                if (stopWords.Contains(word) || word.Length < 3)
                    continue;
                
                // 基础分数
                float score = 1f;
                
                // 应用权重
                if (keywordWeights.ContainsKey(word))
                {
                    score *= keywordWeights[word];
                }
                
                // 长度加成
                if (word.Length > 6)
                {
                    score += 0.2f;
                }
                
                // 词频加成
                var frequency = words.Count(w => w == word);
                if (frequency > 1)
                {
                    score += 0.1f * (frequency - 1);
                }
                
                keywordScores[word] = score;
            }
            
            // 返回得分最高的关键词
            return keywordScores
                .OrderByDescending(kvp => kvp.Value)
                .Take(maxKeywords)
                .Select(kvp => kvp.Key)
                .ToList();
        }
        
        /// <summary>
        /// 计算查询重要性
        /// </summary>
        private float CalculateQueryImportance(ProcessedQuery query)
        {
            float importance = 1f; // 基础重要性
            
            // 基于上下文调整重要性
            switch (query.context)
            {
                case QueryContext.Reflection:
                    importance += 0.5f;
                    break;
                case QueryContext.Planning:
                    importance += 0.3f;
                    break;
                case QueryContext.Social:
                    importance += 0.2f;
                    break;
            }
            
            // 基于关键词调整重要性
            foreach (var keyword in query.keywords)
            {
                if (keywordWeights.ContainsKey(keyword))
                {
                    importance += (keywordWeights[keyword] - 1f) * 0.2f;
                }
            }
            
            // 基于查询长度调整（更长的查询可能更重要）
            if (query.keywords.Count > 5)
            {
                importance += 0.2f;
            }
            
            return Mathf.Clamp(importance, 0.5f, 2f);
        }
        
        /// <summary>
        /// 提取实体
        /// </summary>
        private List<string> ExtractEntities(string cleanedQuery)
        {
            var entities = new List<string>();
            var words = cleanedQuery.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            
            for (int i = 0; i < words.Length; i++)
            {
                var word = words[i];
                
                // 检测人名（首字母大写或常见人名）
                if (IsPersonName(word))
                {
                    entities.Add(word);
                }
                
                // 检测地点名（包含location, place等词后面的词）
                if (i > 0 && (words[i-1] == "at" || words[i-1] == "in" || words[i-1] == "location" || words[i-1] == "place"))
                {
                    entities.Add(word);
                }
                
                // 检测时间实体
                if (IsTimeExpression(word))
                {
                    entities.Add(word);
                }
            }
            
            return entities.Distinct().ToList();
        }
        
        /// <summary>
        /// 检测查询意图
        /// </summary>
        private QueryIntent DetectQueryIntent(string cleanedQuery, QueryContext context)
        {
            var lowerQuery = cleanedQuery.ToLower();
            
            // 基于疑问词检测意图
            if (lowerQuery.StartsWith("what"))
                return QueryIntent.Information;
            
            if (lowerQuery.StartsWith("who"))
                return QueryIntent.Person;
            
            if (lowerQuery.StartsWith("when"))
                return QueryIntent.Time;
            
            if (lowerQuery.StartsWith("where"))
                return QueryIntent.Location;
            
            if (lowerQuery.StartsWith("why"))
                return QueryIntent.Reason;
            
            if (lowerQuery.StartsWith("how"))
                return QueryIntent.Method;
            
            // 基于动词检测意图
            if (lowerQuery.Contains("remember") || lowerQuery.Contains("recall"))
                return QueryIntent.Recall;
            
            if (lowerQuery.Contains("plan") || lowerQuery.Contains("schedule"))
                return QueryIntent.Planning;
            
            if (lowerQuery.Contains("feel") || lowerQuery.Contains("think"))
                return QueryIntent.Opinion;
            
            // 基于上下文检测意图
            switch (context)
            {
                case QueryContext.Conversation:
                    return QueryIntent.Social;
                case QueryContext.Planning:
                    return QueryIntent.Planning;
                case QueryContext.Reflection:
                    return QueryIntent.Reflection;
                case QueryContext.Navigation:
                    return QueryIntent.Location;
                default:
                    return QueryIntent.General;
            }
        }
        
        /// <summary>
        /// 检查是否为人名
        /// </summary>
        private bool IsPersonName(string word)
        {
            // 简化的人名检测
            if (word.Length < 2) return false;
            
            // 首字母大写
            if (char.IsUpper(word[0]))
                return true;
            
            // 常见人名列表（简化）
            var commonNames = new HashSet<string>
            {
                "john", "mary", "mike", "sarah", "david", "lisa", "james", "anna",
                "robert", "maria", "william", "susan", "richard", "karen", "thomas", "nancy"
            };
            
            return commonNames.Contains(word.ToLower());
        }
        
        /// <summary>
        /// 检查是否为时间表达
        /// </summary>
        private bool IsTimeExpression(string word)
        {
            var timeWords = new HashSet<string>
            {
                "morning", "afternoon", "evening", "night", "today", "yesterday", "tomorrow",
                "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday",
                "january", "february", "march", "april", "may", "june", "july", "august",
                "september", "october", "november", "december", "now", "later", "soon", "recently"
            };
            
            return timeWords.Contains(word.ToLower());
        }
        
        /// <summary>
        /// 获取上下文关键词
        /// </summary>
        public Dictionary<string, QueryContext> GetContextKeywords()
        {
            return new Dictionary<string, QueryContext>(contextKeywords);
        }
        
        /// <summary>
        /// 添加上下文关键词
        /// </summary>
        public void AddContextKeyword(string keyword, QueryContext context)
        {
            contextKeywords[keyword.ToLower()] = context;
        }
        
        /// <summary>
        /// 设置关键词权重
        /// </summary>
        public void SetKeywordWeight(string keyword, float weight)
        {
            keywordWeights[keyword.ToLower()] = weight;
        }
    }
    
    /// <summary>
    /// 处理后的查询数据结构
    /// </summary>
    public class ProcessedQuery
    {
        public string originalQuery;        // 原始查询
        public string cleanedQuery;         // 清理后的查询
        public List<string> keywords;       // 提取的关键词
        public QueryContext context;        // 查询上下文
        public QueryIntent intent;          // 查询意图
        public float importanceScore;       // 重要性分数
        public List<string> entities;       // 实体列表
        public float[] embedding;           // 查询嵌入向量
        public DateTime timestamp;          // 处理时间戳
        
        public ProcessedQuery()
        {
            keywords = new List<string>();
            entities = new List<string>();
            timestamp = DateTime.Now;
        }
    }
    
    /// <summary>
    /// 查询意图枚举
    /// </summary>
    public enum QueryIntent
    {
        General,        // 通用
        Information,    // 信息查询
        Person,         // 人物查询
        Time,           // 时间查询
        Location,       // 位置查询
        Reason,         // 原因查询
        Method,         // 方法查询
        Recall,         // 回忆查询
        Planning,       // 计划查询
        Opinion,        // 观点查询
        Social,         // 社交查询
        Reflection      // 反思查询
    }
}